#!/bin/bash

processName=php-fpm
serviceName=hperf-yym
groupName=DEFAULT_GROUP
namespaceId=public
nacosHost=
pythonCmd=python

instanceHost=
instancePort=8123
ephemeral=true

# 参数说明
# cluster : 集群名称
# scheduled :
# ephemeral : true 临时实例
beat="{\"cluster\":\"\",\"ip\":\"${instanceHost}\",\"metadata\":{},\"port\":\"${instancePort}\",\"scheduled\":true,\"serviceName\":\"${serviceName}\",\"weight\":\"1\"}"



# 获取服务
#function getService () {
#    url="${nacosHost}/nacos/v1/ns/service?serviceName=${serviceName}&groupName=${groupName}&namespaceId=${namespaceId}"
#    response=$(curl -sS --location --request GET "$url")
#    # clusters=$(echo $response | $pythonCmd -c "import sys, json; print(json.load(sys.stdin)['clusters'])")
#    clusters=$(echo $response | $pythonCmd -c "import json,sys;obj=json.load(sys.stdin);print(obj['clusters'])")
#    if [ "$clusters" == "[]" ]; then
#        # 服务不存在
#        return 0
#    fi
#    return 1
#}

# 创建服务
#function createService() {
#}
#
## 更新服务
#function updateService() {
#}
#
## 获取实例
#function getInstance () {
#}
#
## 创建实例
#function getInstance () {
#}
#

# 服务注册主流程
#function worker() {
#    # 服务是否存在
#    getService
#    serviceExist=$?
#    if [ "$serviceExist" == 0 ]; then
#        # 服务不存在则创建服务
#        createService
#    else
#        updateService
#    fi
#}

function main() {
    # ps一下 processName 进程在不在
     while [ true ]; do
       isExistProcess
       ret=$?
       if [ "$ret" == 1 ]; then
          url="${nacosHost}/nacos/v1/ns/instance/beat?serviceName=${serviceName}&groupName=${groupName}&ephemeral=${ephemeral}"
         response=$(curl -sS --location --request PUT "$url" --data-urlencode "beat=${beat}")
         echo ${response}
       fi
        sleep 1
     done
}

function isExistProcess() {
    pid=$(ps -ef | grep $processName | grep -v "grep" | awk '{print $2}')
    if [ "$pid" != "" ]; then
      return 1
    else
      return 0
    fi
}

main;

